package com.jhgsys.internal.contractor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.contractor.dto.BaseContractorTeamDto;
import com.jhgsys.internal.contractor.entity.BaseContractor;
import com.jhgsys.internal.contractor.entity.BaseContractorTeam;
import com.jhgsys.internal.contractor.mapper.BaseContractorTeamMapper;
import com.jhgsys.internal.contractor.service.IBaseContractorService;
import com.jhgsys.internal.contractor.service.IBaseContractorTeamService;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.ITenantService;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 承包队设置 Service实现
 *
 * @author admin
 * @date 2024-07-29 14:19:05
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class BaseContractorTeamServiceImpl extends ServiceImpl<BaseContractorTeamMapper, BaseContractorTeam> implements IBaseContractorTeamService {

    @Autowired
    IBaseContractorService contractorService;

    @Autowired
    ITenantService tenantService;

    @Autowired
    IUserService userService;



    /**
     * 查询（分页）
     * @author admin
     * @date 2024-07-29 14:19:05
     * @param request QueryRequest
     * @param baseContractorTeam baseContractorTeam
     * @return IPage<BaseContractorTeam>
    */
    @Override
    public IPage<BaseContractorTeamDto> findBaseContractorTeams(QueryRequest request, BaseContractorTeam baseContractorTeam) {
        LambdaQueryWrapper<BaseContractorTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseContractorTeam::getDeletedFlg, FebsConstant.VALID);
        if(StringUtils.isNotBlank(baseContractorTeam.getTenantId())){
            queryWrapper.eq(BaseContractorTeam::getTenantId, baseContractorTeam.getTenantId());
        }
        if(StringUtils.isNotBlank(baseContractorTeam.getContractorId())){
            queryWrapper.eq(BaseContractorTeam::getContractorId, baseContractorTeam.getContractorId());
        }
        if(StringUtils.isNotBlank(baseContractorTeam.getTeamName())){
            queryWrapper.like(BaseContractorTeam::getTeamName, baseContractorTeam.getTeamName());
        }
        if(StringUtils.isNotBlank(baseContractorTeam.getStatus())){
            queryWrapper.eq(BaseContractorTeam::getStatus, baseContractorTeam.getStatus());
        }

        Page<BaseContractorTeam> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        IPage<BaseContractorTeam> pageResult = this.page(page, queryWrapper);
        List<BaseContractorTeam> teamList = pageResult.getRecords();

        IPage<BaseContractorTeamDto> dtoPageList = new Page<>();
        dtoPageList.setTotal(pageResult.getTotal());
        dtoPageList.setCurrent(pageResult.getCurrent());
        if(!CollectionUtils.isEmpty(teamList)){
            List<BaseContractorTeamDto> dtoList = BeanHelper.copyWithCollection(teamList,BaseContractorTeamDto.class);
            User userParam = new User();
            userParam.setTenantId(baseContractorTeam.getTenantId());
            List<User> userList =  userService.findUserList(userParam);
            dtoList.forEach(item->{
                List<User> teamUserList = userList.stream().filter(user-> item.getContractorId().equals(user.getContractorId()) &&  item.getContractorTeamId().equals(user.getContractorTeamId())).collect(Collectors.toList());
                if(null != teamUserList && teamUserList.size() > 0){
                    item.setTeamUserList(teamUserList);
                }
            });
            dtoPageList.setRecords(dtoList);

        }
        return dtoPageList;
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-07-29 14:19:05
     * @param baseContractorTeam baseContractorTeam
     * @return List<BaseContractorTeam>
     */
    @Override
    public List<BaseContractorTeam> findBaseContractorTeams(BaseContractorTeam baseContractorTeam) {
	    LambdaQueryWrapper<BaseContractorTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseContractorTeam::getDeletedFlg, '0');
		// TODO 设置查询条件
        if(StringUtils.isNotBlank(baseContractorTeam.getTenantId())){
            queryWrapper.eq(BaseContractorTeam::getTenantId,baseContractorTeam.getTenantId());
        }
        if(StringUtils.isNotBlank(baseContractorTeam.getContractorId())){
            queryWrapper.eq(BaseContractorTeam::getContractorId,baseContractorTeam.getContractorId());
        }
        if(StringUtils.isNotBlank(baseContractorTeam.getTeamName())){
            queryWrapper.eq(BaseContractorTeam::getTeamName,baseContractorTeam.getTeamName());
        }
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author admin
    * @date 2024-07-29 14:19:05
    * @param baseContractorTeamId
    * @return BaseContractorTeam
    */
    @Override
    public BaseContractorTeamDto findBaseContractorTeamById(String baseContractorTeamId){
        BaseContractorTeamDto dto = new BaseContractorTeamDto();
        BaseContractorTeam queryTeam = this.baseMapper.selectById(baseContractorTeamId);
        if(ObjectUtils.isNotEmpty(queryTeam)){
            BeanUtils.copyProperties(queryTeam,dto);
        }
        return dto;
    }

    /**
     * 新增
     * @author admin
     * @date 2024-07-29 14:19:05
     * @param baseContractorTeam baseContractorTeam
     */
    @Override
    @Transactional
    public void createBaseContractorTeam(BaseContractorTeamDto baseContractorTeam) {
        baseContractorTeam.setCreatedTime(new Date());
        this.save(baseContractorTeam);
        updateConstructionDept(baseContractorTeam.getTenantId(),baseContractorTeam.getContractorId());
    }

    /**
     * 修改
     * @author admin
     * @date 2024-07-29 14:19:05
     * @param baseContractorTeam baseContractorTeam
     */
    @Override
    @Transactional
    public void updateBaseContractorTeam(BaseContractorTeamDto baseContractorTeam) {
        baseContractorTeam.setUpdatedTime(new Date());
        this.updateById(baseContractorTeam);
        updateConstructionDept(baseContractorTeam.getTenantId(),baseContractorTeam.getContractorId());
    }

    /**
     * 逻辑删除
     * @author admin
     * @date 2024-07-29 14:19:05
     * @param baseContractorTeam baseContractorTeam
     * @param baseContractorTeamIds baseContractorTeamIds
     */
    @Override
    @Transactional
    public void deleteBaseContractorTeam(BaseContractorTeam baseContractorTeam,String baseContractorTeamIds) {
        List<String> list = Arrays.asList(baseContractorTeamIds.split(StringPool.COMMA));
        this.baseMapper.update(baseContractorTeam,new LambdaQueryWrapper<BaseContractorTeam>().in(BaseContractorTeam::getContractorTeamId,list));
	}

    /**
    * 物理删除
    * @author admin
    * @date 2024-07-29 14:19:05
    * @param baseContractorTeamIds baseContractorTeamIds
    */
    @Override
    @Transactional
    public void physicallyDeleteBaseContractorTeam(String baseContractorTeamIds) {
        List<String> list = Arrays.asList(baseContractorTeamIds.split(StringPool.COMMA));
        LambdaQueryWrapper<BaseContractorTeam> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(BaseContractorTeam::getContractorTeamId,list);
        this.remove(wrapper);
    }

    @Override
    public void updateBaseContractorTeamDeletedFlg(BaseContractorTeam contractorTeam) {
        this.baseMapper.update(contractorTeam,new LambdaUpdateWrapper<BaseContractorTeam>()
                .eq(BaseContractorTeam::getContractorTeamId,contractorTeam.getContractorTeamId()));
    }

    /**
     * 更新承包方实施部门信息
     * @param contractorId
     * @return
     */
    @Transactional
    @Override
    public boolean updateConstructionDept(String tenantId, String contractorId){
        BaseContractorTeam contractorTeamParam = new BaseContractorTeamDto();
        contractorTeamParam.setTenantId(tenantId);
        contractorTeamParam.setContractorId(contractorId);
        contractorTeamParam.setStatus("1");
        List<BaseContractorTeam> baseContractorTeamList = findBaseContractorTeams(contractorTeamParam);
        String constructionDeps = "";
        if(null != baseContractorTeamList && baseContractorTeamList.size() > 0){
            List<String> constructionDeptList = baseContractorTeamList.stream().map(BaseContractorTeam::getConstructionDept).distinct().collect(Collectors.toList());
            constructionDeps = String.join(",",constructionDeptList);
        }
        BaseContractor contractorUpdate = new BaseContractor();
        contractorUpdate.setContractorId(contractorId);
        contractorUpdate.setConstructionDepts(constructionDeps);
        contractorService.updateById(contractorUpdate);
        return true;
    }

}
